package com.gwtgeo.service.manager.impl;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.Serializable;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

import com.gwtgeo.service.exception.GwtgeoException;
import com.gwtgeo.service.manager.FileSaveManager;

public class FileSaveManagerImpl implements FileSaveManager {

	private Marshaller marshaller;

	private Unmarshaller unmarshaller;

	private String baseDir;

	public Serializable load(String filename) throws GwtgeoException {
		FileInputStream is = null;
		try {
			try {
				is = new FileInputStream(this.getPath(filename));
				return (Serializable) this.unmarshaller.unmarshal(new StreamSource(is));
			} finally {
				if (is != null) {
					is.close();
				}
			}
		} catch (Exception e) {
			throw new GwtgeoException(e);
		}

	}

	public void save(String filename, Serializable def) throws GwtgeoException {
		FileOutputStream os = null;
		try {
			try {
				os = new FileOutputStream(this.getPath(filename));
				this.marshaller.marshal(def, new StreamResult(os));
			} finally {
				if (os != null) {
					os.close();
				}
			}
		} catch (Exception e) {
			throw new GwtgeoException(e);
		}
	}

	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}

	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}

	public void setBaseDir(String baseDir) {
		this.baseDir = baseDir;
	}

	private String getPath(String filename) {
		if (this.baseDir != null && !baseDir.isEmpty()) {
			if (this.baseDir.endsWith("/") || this.baseDir.endsWith("\\")) {
				return this.baseDir + filename;
			} else {
				return this.baseDir + "/" + filename;
			}
		} else {
			return filename;
		}
	}
}
